//
//  IphoneRootViewController.m
//  atlas
//
//  Created by 你好 on 16/12/28.
//  Copyright © 2016年 xyxNav. All rights reserved.
//

#import "IphoneRootViewController.h"
#import "CustomCollectionViewCell.h"
#import "CustomFlowLayout.h"
#import "CollectionHeaderView.h"
#import "ListViewController.h"
#import "LCZoomTransition.h"
#import "PhotoAlbum.h"
#import "MONActivityIndicatorView.h"
#import <MJRefresh.h>
#import "TopView.h"
#import "CenterScrollView.h"
#import "AboutView.h"
#import "PhotoBrowser.h"
@interface IphoneRootViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MONActivityIndicatorViewDelegate,CenterScrollViewDelegate,MWPhotoBrowserDelegate>

@property (nonatomic,retain)UIImageView *backImageView;
@property (nonatomic,retain)UICollectionView *collectionView;
@property (nonatomic,strong)id myTranstion;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,retain)MONActivityIndicatorView *indicatorView;
@property (nonatomic,strong)Recommend *recommend;
@property (nonatomic,retain)UIScrollView *backScrollView;
@property (nonatomic,retain)UIView *sizeView;
@property (nonatomic,retain)UIScrollView *contentScrollView;
@property (nonatomic,retain)CenterScrollView *centerScrollView;
@property (nonatomic,retain)TopView *topView;
@property (nonatomic,retain)AboutView *aboutView;
@property (nonatomic,retain)PhotoBrowser *photoBrowser;
@property (nonatomic,strong)NSMutableArray *photos;

@end

static NSString *collectionCellIDE=@"collectionCellIDE";
static NSString *collectionHeaderIDE=@"collectionHeaderIDE";

@implementation IphoneRootViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor=[UIColor whiteColor];
    [self.navigationController setNavigationBarHidden:YES];
    self.dataArray=[[NSMutableArray alloc]initWithCapacity:0];
    self.photos=[[NSMutableArray alloc]initWithCapacity:0];
    
    self.backScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    self.backScrollView.showsVerticalScrollIndicator=NO;
    self.backScrollView.showsHorizontalScrollIndicator=NO;
    self.backScrollView.backgroundColor=[UIColor whiteColor];
    self.backScrollView.contentSize=CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height*3);
    [self.view addSubview:self.backScrollView];
    
    self.topView=[[TopView alloc]initWithFrame:CGRectMake(0, 0, self.backScrollView.bounds.size.width, self.backScrollView.bounds.size.height*0.3)];
    [self.topView configUI];
    [self.backScrollView addSubview:self.topView];
    
    self.centerScrollView=[[CenterScrollView alloc]init];
    self.centerScrollView.frame=CGRectMake(0, self.topView.frame.origin.y+self.topView.frame.size.height, self.backScrollView.bounds.size.width, self.backScrollView.bounds.size.height*0.08);
    [self.centerScrollView configUI];
    self.centerScrollView.delegate=self;
    [self.backScrollView addSubview:self.centerScrollView];

    
    self.contentScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, self.centerScrollView.frame.origin.y+self.centerScrollView.frame.size.height, self.backScrollView.bounds.size.width,self.backScrollView.bounds.size.height*0.62)];
    self.contentScrollView.showsVerticalScrollIndicator=NO;
    self.contentScrollView.showsHorizontalScrollIndicator=NO;
    self.contentScrollView.backgroundColor=[UIColor whiteColor];
    self.contentScrollView.pagingEnabled=YES;
    self.contentScrollView.bounces=NO;
    self.contentScrollView.delegate=self;
    self.contentScrollView.contentSize=CGSizeMake(self.contentScrollView.bounds.size.width*2,self.contentScrollView.bounds.size.height);
    [self.backScrollView addSubview:self.contentScrollView];
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.contentScrollView.bounds.size.width, self.contentScrollView.bounds.size.height) collectionViewLayout:layout];
    [self.collectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:collectionCellIDE];
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    self.collectionView.backgroundColor=[UIColor whiteColor];
    [self.collectionView setContentInset:UIEdgeInsetsMake(0, 0, 10, 0)];
    [self.contentScrollView addSubview:self.collectionView];
    
    self.aboutView=[[AboutView alloc]initWithFrame:CGRectMake(self.contentScrollView.bounds.size.width, 0, self.contentScrollView.bounds.size.width, self.contentScrollView.bounds.size.height)];
    [self.aboutView configUI];
    [self.contentScrollView addSubview:self.aboutView];
    
    [self configLeftSize];
    
    
    self.indicatorView = [[MONActivityIndicatorView alloc] init];
    self.indicatorView.delegate=self;
    [self.view addSubview:self.indicatorView];
    
    [self.indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];

    self.backScrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [[UserManager shareInstance]getAllAlbum:YES];
        [[UserManager shareInstance]getRecommend:YES];
        [[UserManager shareInstance]getAboutInfo:YES];
    }];

    NSString *userID=@"13126696627";
    NSString *password=@"123456";
    [[UserManager shareInstance]loginWithUserId:userID andPassword:password];
    [self.indicatorView startAnimating];
    
    
}

-(int)getRandomNumber:(NSInteger)from to:(NSInteger)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}


-(void)configLeftSize
{
    self.contentScrollView.frame=CGRectMake(0, self.centerScrollView.frame.origin.y+self.centerScrollView.frame.size.height, self.backScrollView.bounds.size.width,self.collectionView.contentSize.height+10);
    self.collectionView.frame=CGRectMake(0, 0, self.contentScrollView.bounds.size.width, self.contentScrollView.bounds.size.height);
    self.contentScrollView.contentSize=CGSizeMake(self.contentScrollView.bounds.size.width*2, self.contentScrollView.bounds.size.height);
    
    if ((self.contentScrollView.frame.origin.y+self.contentScrollView.frame.size.height) > self.view.bounds.size.height)
    {
        self.backScrollView.contentSize=CGSizeMake(self.backScrollView.bounds.size.width, self.contentScrollView.frame.origin.y+self.contentScrollView.frame.size.height);
    }
    else
    {
        self.backScrollView.contentSize=CGSizeMake(self.backScrollView.bounds.size.width, self.view.bounds.size.height+100);
    }
    
    [self.view layoutSubviews];
    [self.view layoutIfNeeded];
    
    [self.backScrollView layoutSubviews];
    [self.backScrollView layoutIfNeeded];
    
    [self.topView layoutSubviews];
    [self.topView layoutIfNeeded];
    
    [self.centerScrollView layoutSubviews];
    [self.centerScrollView layoutIfNeeded];
    
    [self.contentScrollView layoutSubviews];
    [self.contentScrollView layoutIfNeeded];
}

-(void)configRightSize
{
    self.aboutView.frame=CGRectMake(self.contentScrollView.bounds.size.width, 0,self.contentScrollView.bounds.size.width,self.aboutView.contentSize.height);
    self.contentScrollView.frame=CGRectMake(0, self.centerScrollView.frame.origin.y+self.centerScrollView.frame.size.height, self.backScrollView.bounds.size.width, self.aboutView.contentSize.height);
    self.contentScrollView.contentSize=CGSizeMake(self.contentScrollView.bounds.size.width*2, self.contentScrollView.bounds.size.height);
    
    if ((self.contentScrollView.frame.origin.y+self.contentScrollView.frame.size.height)>self.view.bounds.size.height)
    {
        self.backScrollView.contentSize=CGSizeMake(self.backScrollView.bounds.size.width, self.contentScrollView.frame.origin.y+self.contentScrollView.frame.size.height);
    }
    else
    {
        self.backScrollView.contentSize=CGSizeMake(self.backScrollView.bounds.size.width, self.view.bounds.size.height);
    }
    
    [self.view layoutSubviews];
    [self.view layoutIfNeeded];
    
    [self.backScrollView layoutSubviews];
    [self.backScrollView layoutIfNeeded];
    
    [self.topView layoutSubviews];
    [self.topView layoutIfNeeded];
    
    [self.centerScrollView layoutSubviews];
    [self.centerScrollView layoutIfNeeded];
    
    [self.contentScrollView layoutSubviews];
    [self.contentScrollView layoutIfNeeded];
}

#pragma mark - OnEventType

-(void)onEventAction:(AppEventType)type object:(id)object
{
    [super onEventAction:type object:object];
    
    switch (type)
    {
        case EVENT_USER_LOGIN_SUCC:
        {
            [self.indicatorView stopAnimating];
            [[UserManager shareInstance]getAllAlbum:NO];
            [[UserManager shareInstance]getRecommend:NO];
            [[UserManager shareInstance]getAboutInfo:NO];
            [[UserManager shareInstance]cacheAllData];
        }
            break;
        case EVENT_GETALLALBUM_SUCC:
        {
            self.dataArray=object;
            
            if ([self.backScrollView.mj_header isRefreshing])
            {
                [self.backScrollView.mj_header endRefreshing];
            }
            [self.collectionView reloadData];
            
            
            [self.collectionView performBatchUpdates:^{
            } completion:^(BOOL finished) {
                if (self.centerScrollView.isLeft)
                {
                    [self configLeftSize];
                }
                else
                {
                    [self configRightSize];
                }
            }];
        }
            break;
        case EVENT_GETRECOMMEND_SUCC:
        {
            self.recommend=object;
            [self.topView configData:self.recommend];
            
            if([self.backScrollView.mj_header isRefreshing])
            {
                [self.backScrollView.mj_header endRefreshing];
            }
            [self.collectionView reloadData];
            
            [self.collectionView performBatchUpdates:^{
            } completion:^(BOOL finished) {
                if (self.centerScrollView.isLeft)
                {
                    [self configLeftSize];
                }
                else
                {
                    [self configRightSize];
                }            }];
        }
            break;
        case EVENT_GETABOUTINFO_SUCC:
        {
            [self.aboutView configData:object];
            
            if ([self.backScrollView.mj_header isRefreshing])
            {
                [self.backScrollView.mj_header endRefreshing];
            }
            [self.collectionView reloadData];
            
            
            [self.collectionView performBatchUpdates:^{
            } completion:^(BOOL finished) {
                if (self.centerScrollView.isLeft)
                {
                    [self configLeftSize];
                }
                else
                {
                    [self configRightSize];
                }
            }];
        }
            break;
        case EVENT_USER_LOGIN_FAILED:
        case EVENT_GETABOUTINFO_FAIL:
        case EVENT_GETALLALBUM_FAIL:
        case EVENT_GETRECOMMEND_FAIL:
        {
            [self.indicatorView stopAnimating];
        }
            break;
        default:
            break;
    }
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.collectionView reloadData];
}

#pragma mark - <UICollectionDelegate,UICollectionViewDataSource>

//显示header和footer的回调方法

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    if (kind == UICollectionElementKindSectionHeader)
//    {
//        CollectionHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:collectionHeaderIDE forIndexPath:indexPath];
//        if (self.recommend)
//        {
//            [view configData:self.recommend];
//            [view.coverViewBtn addTarget:self action:@selector(coverViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//        }
//        return view;
//    }
//    return nil;
//}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:collectionCellIDE forIndexPath:indexPath];
    PhotoAlbum *photoAlbum=[self.dataArray objectAtIndex:indexPath.row];
    [cell configData:photoAlbum];
    return cell;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 0, 10);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.collectionView.bounds.size.width-30)/2, (self.collectionView.bounds.size.width-30)/2/16*10);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PhotoAlbum *photoAlbum=[self.dataArray objectAtIndex:indexPath.row];
        if ([[UserDefault objectForKey:ISFROMLISTVC] boolValue]==YES)
    {
        if (self.myTranstion)
        {
            self.navigationController.delegate=nil;
            self.myTranstion=nil;
        }
        NSArray *transtionArray=@[@"CEPortalTranstion",@"LCZoomTransition",@"CEFlipTranstion",@"CEFoldTranstion",@"CEExplodeTranstion",@"CEFBTranstion"];
        NSInteger count=transtionArray.count-1;
        NSString *className=[transtionArray objectAtIndex: [self getRandomNumber:0 to:count]];
        
        self.myTranstion = [[NSClassFromString(className) alloc] initWithNavigationController:self.navigationController];
        
        ListViewController *listVC=[[ListViewController alloc]init];
        listVC.prevViewController=self;
        listVC.photoAlbum=photoAlbum;
        [self.navigationController pushViewController:listVC animated:YES];
    }
    else
    {
        [self.photos removeAllObjects];
        
        for (Photo *photo in photoAlbum.photoArray)
        {
            NSURL *imageUrl=[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@?token=%@",GETIMAGE_URL,photo.imageUrl,[UserManager shareInstance].userToken]];
            MWPhoto *p=[MWPhoto photoWithURL:imageUrl];
            [self.photos addObject:p];
        }
        
        BOOL displayActionButton = YES;
        BOOL displaySelectionButtons = NO;
        BOOL displayNavArrows = NO;
        BOOL enableGrid = NO;
        BOOL startOnGrid = NO;
        BOOL autoPlayOnAppear = NO;
        
        self.photoBrowser = [[PhotoBrowser alloc] initWithDelegate:self];
        self.photoBrowser.photoAlbum=photoAlbum;
        self.photoBrowser.displayActionButton = displayActionButton;
        self.photoBrowser.displayNavArrows = displayNavArrows;
        self.photoBrowser.displaySelectionButtons = displaySelectionButtons;
        self.photoBrowser.alwaysShowControls = displaySelectionButtons;
        self.photoBrowser.zoomPhotosToFill = NO;
        self.photoBrowser.enableGrid = enableGrid;
        self.photoBrowser.startOnGrid = startOnGrid;
        self.photoBrowser.enableSwipeToDismiss = NO;
        self.photoBrowser.autoPlayOnAppear = autoPlayOnAppear;
        [self.photoBrowser setCurrentPhotoIndex:0];
        [self.navigationController pushViewController:self.photoBrowser animated:YES];
    }
}


- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        [self.collectionView performBatchUpdates:^{
            [self.collectionView setCollectionViewLayout:self.collectionView.collectionViewLayout animated:YES];
        } completion:nil];
    }];
}


//我们看到第二个参数coordinator，它的类型是UIViewControllerTransitionCoordinator，它能响应VC转换进度，并且提供了以下方法：
- (BOOL)animateAlongsideTransition:(void (^)(id<UIViewControllerTransitionCoordinatorContext> context))animation
                        completion:(void (^)(id<UIViewControllerTransitionCoordinatorContext> context))completion
{
    return YES;
}

//-(void)didSelectedItem:(NSInteger)pageNumber andInfo:(NSDictionary *)infoDict
//{
//    if (self.myTranstion)
//    {
//        self.navigationController.delegate=nil;
//        self.myTranstion=nil;
//    }
//    NSArray *transtionArray=@[@"CEPortalTranstion",@"LCZoomTransition",@"CEFlipTranstion",@"CEFoldTranstion",@"CEExplodeTranstion",@"CEFBTranstion"];
//    NSInteger count=transtionArray.count-1;
//    NSString *className=[transtionArray objectAtIndex: [self getRandomNumber:0 to:count]];
//    
//    self.myTranstion = [[NSClassFromString(className) alloc] initWithNavigationController:self.navigationController];
//    
//    ListViewController *listVC=[[ListViewController alloc]init];
//    listVC.prevViewController=self;
//    [self.navigationController pushViewController:listVC animated:YES];
//}

//#pragma mark - CollectionHeaderViewDelegate
//
//-(void)coverViewBtnClick:(UIButton *)button
//{
//    if (self.myTranstion)
//    {
//        self.navigationController.delegate=nil;
//        self.myTranstion=nil;
//    }
//    NSArray *transtionArray=@[@"CEPortalTranstion",@"LCZoomTransition",@"CEFlipTranstion",@"CEFoldTranstion",@"CEExplodeTranstion",@"CEFBTranstion"];
//    NSInteger count=transtionArray.count-1;
//    NSString *className=[transtionArray objectAtIndex: [self getRandomNumber:0 to:count]];
//    
//    self.myTranstion = [[NSClassFromString(className) alloc] initWithNavigationController:self.navigationController];
//    
//    ListViewController *listVC=[[ListViewController alloc]init];
//    listVC.prevViewController=self;
//    listVC.recommend=self.recommend;
//    listVC.sourceFrom=SourceFrom_Recommend;
//    [self.navigationController pushViewController:listVC animated:YES];
//}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    return [self.photos objectAtIndex:index];
}


#pragma mark - UIScrollViewDelegate

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView==self.contentScrollView)
    {
        int index=scrollView.contentOffset.x/scrollView.bounds.size.width;
        if (index==0)
        {
            [self.centerScrollView leftButtonClick:nil];
        }
        else if(index==1)
        {
            [self.centerScrollView rightButtonClick:nil];
        }
    }
}

#pragma mark - CenterScrollViewDelegate
-(void)didLeftButonClick:(CenterScrollView *)scrollView
{
    [self.contentScrollView scrollRectToVisible:CGRectMake(0, 0, self.contentScrollView.bounds.size.width, self.contentScrollView.bounds.size.height) animated:YES];
}

-(void)didRightButtonClick:(CenterScrollView *)scrollView
{
    [self.contentScrollView scrollRectToVisible:CGRectMake(self.contentScrollView.bounds.size.width, 0, self.contentScrollView.bounds.size.width, self.contentScrollView.bounds.size.height) animated:YES];
    
    [self configRightSize];
    

}



#pragma mark

- (BOOL)shouldAutorotate NS_AVAILABLE_IOS(6_0)
{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0)
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation NS_AVAILABLE_IOS(6_0)
{
    return UIInterfaceOrientationPortrait;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
